package com.chen.exception;

import com.chen.core.model.CommonResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理类，主要对报错信息脱敏
 *
 * @version 1.0
 * @author: chenguangde
 * @createTime: 2021年06月27日 下午3:11
 */
@Configuration
@ControllerAdvice
public class GlobalException {

    private static final Logger log = LoggerFactory.getLogger(GlobalException.class);

    /**
     * 获取国际化消息
     *
     * @param e 异常
     * @return
     */
//    public String getMessage(BaseException e) {
//        String code = "response." + e.getResponseEnum().toString();
//        String message = unifiedMessageSource.getMessage(code, e.getArgs());
//
//        if (message == null || message.isEmpty()) {
//            return e.getMessage();
//        }
//
//        return message;
//    }

    /**
     * 业务异常
     *
     * @param e 异常
     * @return CommonResponseBean 异常结果
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonResponseBean<?> handleBusinessException(BaseException e) {
        log.error("业务异常：", e);
        BaseExceptionEnum exceptionEnum = e.getExceptionEnum();
        return CommonResponseBean.fail(exceptionEnum.getCode(), exceptionEnum.getMessage());
    }

    /**
     * 自定义异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public CommonResponseBean<?> handleBaseException(BaseException e) {
        log.error("业务异常：", e);
        BaseExceptionEnum exceptionEnum = e.getExceptionEnum();
        return CommonResponseBean.fail(exceptionEnum.getCode(), exceptionEnum.getMessage());
    }

    /**
     * Controller上一层相关异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler({
            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            // BindException.class,
            // MethodArgumentNotValidException.class
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    @ResponseBody
    public CommonResponseBean<?> handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        String code = ExceptionEnum.SERVER_ERROR.getCode();
        try {
            ExceptionEnum servletExceptionEnum = ExceptionEnum.valueOf(e.getClass().getSimpleName());
            code = servletExceptionEnum.getCode();
        } catch (IllegalArgumentException e1) {
            log.error("class [{}] not defined in enum {}", e.getClass().getName(), ExceptionEnum.class.getName());
        }

        String message = ExceptionEnum.SERVER_ERROR.getMessage();
        return CommonResponseBean.fail(code, message);
    }


    /**
     * 参数绑定异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public CommonResponseBean<?> handleBindException(BindException e) {
        log.error("参数绑定校验异常", e);
        return wrapperBindingResult(e.getBindingResult());
    }

    /**
     * 参数校验异常，将校验失败的所有异常组合成一条错误信息
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResponseBean<?> handleValidException(MethodArgumentNotValidException e) {
        log.error("参数绑定校验异常", e);
        return wrapperBindingResult(e.getBindingResult());
    }

    /**
     * 包装绑定异常结果
     *
     * @param bindingResult 绑定结果
     * @return 异常结果
     */
    private CommonResponseBean<?> wrapperBindingResult(BindingResult bindingResult) {
        StringBuilder msg = new StringBuilder();

        for (ObjectError error : bindingResult.getAllErrors()) {
            msg.append(", ");
            if (error instanceof FieldError) {
                msg.append(((FieldError) error).getField()).append(": ");
            }
            msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
        }
        return CommonResponseBean.fail(ExceptionEnum.VALID_ERROR.getCode(), msg.substring(2));
    }

    /**
     * 未定义异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResponseBean<?> handleException(Exception e) {
        log.error("未定义异常", e);
        String code = ExceptionEnum.SERVER_ERROR.getCode();
        String message = ExceptionEnum.SERVER_ERROR.getMessage();
        return CommonResponseBean.fail(code, message);
    }
}
